import db from '../config/DataSource'
import { User } from '../entity/User'
import { Service } from 'typedi'

@Service("userService")
export class UserService {

    userRepository
    constructor() {
        this.userRepository = db.getRepository(User)
    }

    async queryUserList() {
        try {
            const [users, count] = await this.userRepository.findAndCount()
            if (!users) throw new Error('No users found')
            return {
                data: users,
                total: count
            }
        } catch (error) {
            console.error('Error fetching user list:', error)
            throw new Error('Failed to fetch user list')
        }
    }

    async save(userDto: User): Promise<User> {
        userDto.userPwd = "e10adc3949ba59abbe56e057f20f883e";
        return await this.userRepository.save(userDto)
    }

    async findOne(id: number): Promise<User | null> {
        return await this.userRepository.findOneById(id)
    }

    async delete(id: number): Promise<void> {
        await this.userRepository.delete(id);
    }

}
